package cn.congine.wizarpos.mall.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.common.RespMessage;
import cn.congine.wizarpos.mall.model.WxAddress;
import cn.congine.wizarpos.mall.model.WxOrderDetail;
import cn.congine.wizarpos.mall.model.open.AddressDetailOutput;
import cn.congine.wizarpos.mall.model.open.DefaultAddressInput;
import cn.congine.wizarpos.mall.model.open.AddressDetailInput;
import cn.congine.wizarpos.mall.model.open.CommonOutput;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.DefaultAddressOutput;
import cn.congine.wizarpos.mall.model.open.GetShoppingCartInput;
import cn.congine.wizarpos.mall.model.open.GetShoppingCartOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryInput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryOutput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryOutput.Result;
import cn.congine.wizarpos.mall.model.open.WechartOrder;
import cn.congine.wizarpos.mall.model.open.WechartOrderDetailInput;
import cn.congine.wizarpos.mall.model.open.WechartOrderOutput;
import cn.congine.wizarpos.mall.model.open.WxOrderPayInput;
import cn.congine.wizarpos.mall.model.open.WxOrderSubmitInput;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.Utils;
import cn.congine.wizarpos.mall.vo.WxShoppingCartItem;

@Controller
@RequestMapping(value = "/confirm_order")
public class ConfirmOrderAction {
	private static Logger logger = Logger.getLogger(ConfirmOrderAction.class);
//	@Autowired
//	private ErpProductPicDefService erpProductPicDefService;
//
//	@Autowired
//	private WxAddressService wxAddressService;
//
//	@Autowired
//	private WxOrderService wxOrderService;
//
//	@Autowired
//	private WxOrderDetailService wxOrderDetailService;
//
//	@Autowired
//	private WxShoppingCartItemService wxShoppingCartItemService;
//
//	@Autowired
//	private WxShoppingCartService wxShoppingCartService;
//
//	@Autowired
//	private ErpProductService erpProductService;
//
//	@Autowired
//	private MrtMerchantCardService mrtMerchantCardService;
//
//	@Autowired
//	private SysTableKeyService sysTableKeyService;
//
//	@Autowired
//	private PayTranLogService payTranLogService;

	@Autowired
	private WPosHttpClient wposHttpClient;

//	@Autowired
//	private SysMerchantDefService sysMerchantDefService;

//
//	@Autowired
//	private WxThirdAuthentication wxAuthentication;

	@Resource(name = "messageSource")
	private MessageSource messageSource;

//	@Autowired
//	private WeiXinTemplateService templateService;
	
	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;
	/**
	 * 购物车订单提交并支付
	 * 
	 * @param openId
	 * @param mid
	 * @param cartId
	 * @param dispatchType
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/create_order")
	public @ResponseBody RespMessage createOrder(
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "cartId", required = false) String cartId,
			@RequestParam(value = "productId", required = false) String productId,
			@RequestParam(value = "orderId", required = false) String oldOrderId,
			@RequestParam(value = "addressId", required = false) String addressId,
			@RequestParam(value = "dispatchType") String dispatchType,
			@RequestParam(value = "token") String token,
			HttpServletRequest httpRequest) throws Exception {
		RespMessage resp = new RespMessage();
		if (Utils.isRepeatSubmit(httpRequest, token)) {
			resp.setCode(1);
			resp.setMessage("订单重复提交");
			return resp;
		}

		String path = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		// 请求开放平台 提交订单
		WxOrderSubmitInput submitInput = new WxOrderSubmitInput();
		submitInput.setMid(mid);
		submitInput.setOpenId(openId);
		submitInput.setAddressId(addressId);
		submitInput.setCartId(cartId);
		submitInput.setDispatchType(dispatchType);
		submitInput.setOrderId(oldOrderId);
		submitInput.setPrint(true);
		submitInput.setProductId(productId);
		submitInput.setUrl(path+ "/wizarpos-mall-sole/wx_order_detail/get_order_detail?mid=" + mid + "&orderId=");//add mid xudongdong
		
		CommonResultOutput submitOuptut = (CommonResultOutput) wizarposOpenRestClient.post(submitInput, "/wxshop/order/submit", CommonResultOutput.class);
		
		if ("0".equals(submitOuptut.getCode())) {
			Utils.removeSessionToken(httpRequest);
			Map<String, String> submitResult = (Map<String, String>)submitOuptut.getResult();
			String orderId = submitResult.get("orderId");
			if ("4".equals(dispatchType) || "5".equals(dispatchType)) { 
				
				// 会员卡支付请求开放平台 支付订单
				WxOrderPayInput payInput = new WxOrderPayInput();
				payInput.setMid(mid);
				payInput.setOpenId(openId);
				payInput.setOrderId(orderId);
				payInput.setPayAmount(submitResult.get("amount"));
				payInput.setPrint(true);
				payInput.setUrl(path + "/wizarpos-mall-sole/wx_order_detail/get_order_detail?mid=" + mid + "&orderId=" + orderId);//add mid xudongdong
				CommonOutput payOuptut = (CommonOutput) wizarposOpenRestClient.post(payInput, "/wxshop/pay", CommonOutput.class);
			
				if ("0".equals(payOuptut.getCode())) {
					// 返回订单号
					resp.setObj(orderId);
					resp.setCode(0);
					resp.setMessage("订单提交成功");
					return resp;
				} else if ("60010".equals(payOuptut.getCode())) {//会员卡余额不足					
					resp.setObj(orderId);
					resp.setCode(3);
					resp.setMessage(payOuptut.getMessage());
					return resp;
				} else {
					resp.setObj(orderId);
					resp.setCode(3);
					resp.setMessage("支付失败");
					return resp;					
				}
			} else if ("2".equals(dispatchType) || "3".equals(dispatchType)) {
				resp.setObj(orderId);
				resp.setCode(2);
				resp.setMessage("订单提交成功");
				return resp;
			} else {
				resp.setObj(orderId);
				resp.setCode(0);
				resp.setMessage("订单提交成功");
				return resp;
			}
			
		} else {
			// 返回订单号
			resp.setCode(1);
			resp.setMessage("提交失败");
			return resp;
		}
	}

	/**
	 * 购物车准备确认订单页面数据
	 * 
	 * @param openId
	 * @param mid
	 * @param cartId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/set_order")
	public ModelAndView setOrder(@RequestParam(value = "mid") String mid,
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "cartId") String cartId,
			HttpServletRequest httpRequest) throws Exception {
//		MrtMerchantCard merchantCard = mrtMerchantCardService
//				.getMrtMerchantCard(mid, openId);
//		SysMerchantDef merchantDef = sysMerchantDefService
//				.getSysMerchantDefByMid(mid);
		Map<String, Object> data = new HashMap<String, Object>();
//		// 判断当前的微信号是否为此商户的注册会员，
//		if (merchantCard == null) {
//			data.put("mid", mid);
//			data.put("openId", openId);
//			return new ModelAndView("card/receive_card", data);
//		}

//		List<cn.congine.wizarpos.mall.vo.WxShoppingCartItem> items = wxShoppingCartItemService
//				.getWxShoppingCartItemListByCartId(cartId);
		
		GetShoppingCartInput input = new GetShoppingCartInput();
		input.setMid(mid);
		input.setOpenId(openId);
		GetShoppingCartOutput output = (GetShoppingCartOutput) wizarposOpenRestClient.post(input, "/wxshop/get_cart_list", GetShoppingCartOutput.class);								
		if (!SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
			if (SysConstants.NO_MEMBER.equals(output.getCode())) {
				data.put("mid", mid);
				data.put("openId", openId);
				return new ModelAndView("card/receive_card", data);
			}
		}
		// 获取购物车里的商品信息
		List<WxShoppingCartItem> items = output.getWxShoppingCartItemList();
		
		// 获取会员信息
		WeChartMemberInfoQueryInput memberInput = new WeChartMemberInfoQueryInput();
		memberInput.setMid(mid);
		memberInput.setOpenId(openId);
		WeChartMemberInfoQueryOutput memberOut = (WeChartMemberInfoQueryOutput) wizarposOpenRestClient.post(memberInput, "/wechart/info/query", WeChartMemberInfoQueryOutput.class);								
		String cardNo = null;
		if (SysConstants.OPEN_SUCCESS.equals(memberOut.getCode())) {
			Result memberInfo = memberOut.getResult();
			cardNo = memberInfo.getCardNo();
			data.put("cardId", memberInfo.getId());
			
		}
		
		//处理会员折扣价
		StringBuffer productIds = new StringBuffer();
		if (items != null && !items.isEmpty()) {
			for (WxShoppingCartItem cartitem : items) {
				productIds.append(cartitem.getProductId());
				productIds.append(",");
			}
			productIds.deleteCharAt(productIds.length()-1);
		}
		Map<String, Integer> priceMap = wposHttpClient.priceByRule(mid, cardNo, productIds.toString());
		if (priceMap != null) {
			if (items != null && !items.isEmpty()) {
				for (WxShoppingCartItem cartitem : items) {
					Integer price = priceMap.get(cartitem.getProductId());
					if (price != null) {
						cartitem.setProductPrice(price);
					}
				}
			}
		}
		
		//计算总金额
		int amount = 0;
		if (items != null && !items.isEmpty()) {
			for (WxShoppingCartItem cartitem : items) {
				amount += cartitem.getProductPrice() * cartitem.getProductNum();
				cartitem.setShowPrice(Utils.formatAmount(cartitem
						.getProductPrice()));
//				cartitem.setPicUrl(getPrituce(cartitem.getProductId()));
				if (StringUtils.isEmpty(cartitem.getPicUrl())) {
					cartitem.setPicUrl(SysConstants.DEFAULT_PICTURE);
				} else {
					cartitem.setPicUrl(Function.dealGridPicUrl(cartitem.getPicUrl(), 150, 150));
				}
				cartitem.setProductName(cartitem.getProductName().length() > 20 ? 
						cartitem.getProductName().substring(0,20)+"..." 
						: cartitem.getProductName());
			}
		}
		
		String sumStr = Utils.formatAmount(amount);// 所有商品总金额

//		String cardId = card == null ? "" : card.getId();
//		WxAddress address = wxAddressService.getDefaultWxAddress(cardId);
		DefaultAddressInput in = new DefaultAddressInput();
		in.setMid(mid);
		in.setOpenId(openId);
		DefaultAddressOutput out = (DefaultAddressOutput) wizarposOpenRestClient.post(in, "/address/default", DefaultAddressOutput.class);								
		if (SysConstants.OPEN_SUCCESS.equals(out.getCode())) {
			WxAddress address = (WxAddress) out.getWxAddress();
			data.put("address", address);
		}
		
		data.put("mid", mid);
		data.put("openId", openId);
//		data.put("cardId", cardId);
		data.put("cartId", cartId);
		data.put("sum", sumStr);
		data.put("items", items);
//		data.put("merchantDef", merchantDef);

		Utils.setSessionToken(httpRequest);

		return new ModelAndView("order/order", data);
	}

	@RequestMapping(value = "/set_order_id")
	public ModelAndView setOrderById(
			@RequestParam(value = "orderId") String orderId,
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "openId") String openId,
			HttpServletRequest httpRequest) throws Exception {
		// 获取订单信息
		WechartOrderDetailInput orderInput = new WechartOrderDetailInput();
		orderInput.setMid(mid);
		orderInput.setOrderId(orderId);
		WechartOrderOutput orderOut = (WechartOrderOutput) wizarposOpenRestClient.post(orderInput, "/order/detail", WechartOrderOutput.class);								
		if (!SysConstants.OPEN_SUCCESS.equals(orderOut.getCode())) {
			// TODO 订单错误
		}
		WechartOrder wxOrder = orderOut.getResult();
		List<WxOrderDetail> details = wxOrder.getOrderDetail();
//		WxOrder wxOrder = wxOrderService.getWxOrderByOrderId(orderId);
//		MrtMerchantCard card = mrtMerchantCardService.getMrtMerchantCard(mid,
//				openId);
		
		//处理会员折扣价
		StringBuffer productIds = new StringBuffer();
		if (details != null && !details.isEmpty()) {
			for (WxOrderDetail item : details) {
				productIds.append(item.getProductId());
				productIds.append(",");
			}
			productIds.deleteCharAt(productIds.length()-1);
		}
		
		// 获取会员信息
		WeChartMemberInfoQueryInput memberInput = new WeChartMemberInfoQueryInput();
		memberInput.setMid(mid);
		memberInput.setOpenId(openId);
		WeChartMemberInfoQueryOutput memberOut = (WeChartMemberInfoQueryOutput) wizarposOpenRestClient.post(memberInput, "/wechart/info/query", WeChartMemberInfoQueryOutput.class);								
		String cardNo = null;
		String cardId = null;
		if (SysConstants.OPEN_SUCCESS.equals(memberOut.getCode())) {
			Result memberInfo = memberOut.getResult();
			cardNo = memberInfo.getCardNo();
			cardId = memberInfo.getId();
		}
				
		Map<String, Integer> priceMap = wposHttpClient.priceByRule(mid, cardNo, productIds.toString());
		if (priceMap != null) {
			if (details != null && !details.isEmpty()) {
				for (WxOrderDetail item : details) {
					Integer price = priceMap.get(item.getProductId());
					if (price != null) {
						item.setPrice(price);
					}
				}
			}
		}

		//显示商品列表
		int amount = Integer.valueOf(wxOrder.getAmount());
		List<WxShoppingCartItem> items = new ArrayList<WxShoppingCartItem>();
		if (details != null && !details.isEmpty()) {
			for (WxOrderDetail item : details) {
				WxShoppingCartItem cartItem = new WxShoppingCartItem();
				String productId = item.getProductId();
				cartItem.setShowPrice(Utils.formatAmount((item.getPrice())));
//				cartItem.setPicUrl(getPrituce(productId));
				if (StringUtils.isEmpty(item.getPicUrl())) {
					cartItem.setPicUrl(SysConstants.DEFAULT_PICTURE);
				} else {
					cartItem.setPicUrl(Function.dealGridPicUrl(item.getPicUrl(), 150, 150));
				}
				cartItem.setProductId(productId);
				cartItem.setProductName(item.getProductName().length() > 20 ? 
						item.getProductName().substring(0,20)+"..." 
						: item.getProductName());
				cartItem.setProductNum(item.getQty());
				cartItem.setProductPrice(item.getPrice());
				items.add(cartItem);
			}
		}
		// 所有商品总金额
		String sumStr = Utils.formatAmount(amount);

//		String cardId = card == null ? "" : card.getId();
		String addressId = wxOrder.getAddressId();
		WxAddress address = null;
		AddressDetailInput in = new AddressDetailInput();
		in.setMid(mid);
		in.setId(addressId);
		AddressDetailOutput out = (AddressDetailOutput) wizarposOpenRestClient.post(in, "/address/detail", AddressDetailOutput.class);								
		if (SysConstants.OPEN_SUCCESS.equals(out.getCode())) {
			address = (WxAddress) out.getResult();
		}
		
//		if (addressId != null) {// 获取原订单地址
//			address = wxAddressService.getWxAddressId(addressId);
//		}
//		if (address == null) {// 原订单地址不存在，获取默认地址
//			address = wxAddressService.getDefaultWxAddress(cardId);
//		}

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("address", address);
		data.put("orderId", orderId);
		data.put("mid", mid);
		data.put("openId", openId);
		data.put("cardId", cardId);		
		data.put("cartId", "");
		data.put("sum", sumStr);
		data.put("items", items);

		Utils.setSessionToken(httpRequest);

		return new ModelAndView("order/order", data);
	}

	/**
	 * 准备立即购买确认订单页面数据
	 * 
	 * @param openId
	 * @param mid
	 * @param cartId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/set_order_product")
	public ModelAndView setOrderByProduct(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "productId") String productId,
			HttpServletRequest httpRequest) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		
//		MrtMerchantCard merchantCard = mrtMerchantCardService
//				.getMrtMerchantCard(mid, openId);
//		SysMerchantDef merchantDef = sysMerchantDefService
//				.getSysMerchantDefByMid(mid);
		// 判断当前的微信号是否为此商户的注册会员，
//		if (merchantCard == null) {
//			data.put("mid", mid);
//			data.put("openId", openId);
//			return new ModelAndView("card/receive_card", data);
//		}
		// 获取会员信息
		WeChartMemberInfoQueryInput memberInput = new WeChartMemberInfoQueryInput();
		memberInput.setMid(mid);
		memberInput.setOpenId(openId);
		WeChartMemberInfoQueryOutput memberOut = (WeChartMemberInfoQueryOutput) wizarposOpenRestClient.post(memberInput, "/wechart/info/query", WeChartMemberInfoQueryOutput.class);								
		String cardNo = null;
		if (SysConstants.OPEN_SUCCESS.equals(memberOut.getCode())) {
			Result memberInfo = memberOut.getResult();
			cardNo = memberInfo.getCardNo();
			data.put("cardId", memberInfo.getId());
		} else if (SysConstants.NO_MEMBER.equals(memberOut.getCode())) {
			data.put("mid", mid);
			data.put("openId", openId);
			return new ModelAndView("card/receive_card", data);
		}

//		ErpProduct product = erpProductService.getErpProductById(productId);
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setProductId(productId);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		Merchandise product = null;
		if (SysConstants.OPEN_SUCCESS.equals(producthotOutput.getCode())) {
			List<Merchandise> products = producthotOutput.getResult();
			if (products != null && !products.isEmpty()) {
				product = products.get(0);
				
				WxShoppingCartItem cartitem = new WxShoppingCartItem();
//				cartitem.setPicUrl(getPrituce(productId));
				if (StringUtils.isEmpty(product.getPicUrl())) {
					cartitem.setPicUrl(SysConstants.DEFAULT_PICTURE);
				} else {
					cartitem.setPicUrl(Function.dealGridPicUrl(product.getPicUrl(), 150, 150));
				}
				cartitem.setProductId(productId);
				cartitem.setProductName(product.getName().length() > 20 ? 
						product.getName().substring(0,20)+"..." 
						: product.getName());
				cartitem.setProductNum(1);
				
				//处理会员折扣价
				Map<String, Integer> priceMap = wposHttpClient.priceByRule(mid, cardNo, product.getProductId());
/*				int amount = 0;
				if (priceMap != null) { //
					amount = priceMap.get(product.getProductId());
				} else if (product.getMemberPrice() != null) {
					amount = Integer.valueOf(product.getMemberPrice()); // 会员结算
				} else {
					amount = Integer.valueOf(product.getPrice());
				}
				String amountStr = Utils.formatAmount(amount);*/
				String amountStr;
				if (priceMap != null) { //
					amountStr = Utils.formatAmount(priceMap.get(product.getProductId()));
				} else if (product.getMemberPrice() != null) {
					amountStr = product.getMemberPrice(); // 会员结算
				} else {
					amountStr = product.getPrice();
				}				
				cartitem.setShowPrice(amountStr);
				List<WxShoppingCartItem> items = new ArrayList<WxShoppingCartItem>();
				items.add(cartitem);
				// 商品总金额
				data.put("sum", amountStr);
				data.put("items", items);
			}
			
		}
		
//		MrtMerchantCard card = mrtMerchantCardService.getMrtMerchantCard(mid,
//				openId);
//		String cardId = card == null ? "" : card.getId();
//		WxAddress address = wxAddressService.getDefaultWxAddress(cardId);
		DefaultAddressInput in = new DefaultAddressInput();
		in.setMid(mid);
		in.setOpenId(openId);
		DefaultAddressOutput out = (DefaultAddressOutput) wizarposOpenRestClient.post(in, "/address/default", DefaultAddressOutput.class);								
		if (SysConstants.OPEN_SUCCESS.equals(out.getCode())) {
			WxAddress address = (WxAddress) out.getWxAddress();
			data.put("address", address);
		}
		
		data.put("mid", mid);
		data.put("openId", openId);
//		data.put("cardId", cardId);		
		data.put("cartId", "");
//		data.put("sum", amountStr);
		data.put("productId", productId);
//		data.put("items", items);
//		data.put("merchantDef", merchantDef);

		Utils.setSessionToken(httpRequest);

		return new ModelAndView("order/order", data);
	}

//	private String getPrituce(String productId) {
//		ErpProduct erpP = erpProductService.getErpProductById(productId);
//		if (erpP != null && null != erpP.getPicId()
//				&& !erpP.getPicId().equals("")) {
//			String picIds[] = erpP.getPicId().split(",");
//			if (picIds.length > 0) {
//				// 注意id为空的情况
//				if (erpProductPicDefService.getErpProductPicDefById(picIds[0]) != null)
//					return Function.dealGridPicUrl(erpProductPicDefService
//							.getErpProductPicDefById(picIds[0]).getAddress(),
//							150, 150);
//			}
//		} else {
//			return SysConstants.DEFAULT_PICTURE;
//		}
//		return "";
//	}

	/**
	 * 准备确认订单页面数据
	 * 
	 * @param openId
	 * @param mid
	 * @param cartId
	 * @return
	 */
	@RequestMapping(value = "/order_ok")
	public ModelAndView orderOk(@RequestParam(value = "mid") String mid,
			@RequestParam(value = "orderId") String orderId) {
		Map<String, Object> data = new HashMap<String, Object>();
//		WxOrder order = wxOrderService.getWxOrderByOrderId(orderId);
		// 获取订单信息
		WechartOrderDetailInput orderInput = new WechartOrderDetailInput();
		orderInput.setMid(mid);
		orderInput.setOrderId(orderId);
		WechartOrderOutput orderOut = (WechartOrderOutput) wizarposOpenRestClient.post(orderInput, "/order/detail", WechartOrderOutput.class);								
		if (!SysConstants.OPEN_SUCCESS.equals(orderOut.getCode())) {
			// TODO 订单错误
		}
		WechartOrder order = orderOut.getResult();
		switch (order.getDispatchType()) {
		case "1":
			data.put("dispatchType", "货到付款");
			break;
		case "2":
			data.put("dispatchType", "微信支付送货上门");
			break;
		case "3":
			data.put("dispatchType", "微信支付到店提货");
			break;
		case "4":
			data.put("dispatchType", "会员卡支付送货上门");
			break;
		case "5":
			data.put("dispatchType", "会员卡支付到店提货");
			break;
		default:
			break;
		}
		data.put("orderId", Function.getShowWxOrderId(orderId));
		data.put("amount", Utils.formatAmount(order.getAmount()));
		data.put("mid", order.getMid());
		data.put("openId", order.getOpenId());
		return new ModelAndView("order/orderok", data);
	}
	
	/**
	 * 准备确认订单页面数据
	 * 
	 * @param openId
	 * @param mid
	 * @param cartId
	 * @return
	 */
	@RequestMapping(value = "/order_unpay")
	public ModelAndView orderUnpay(@RequestParam(value = "mid") String mid,
			@RequestParam(value = "orderId") String orderId) {
		Map<String, Object> data = new HashMap<String, Object>();
//		WxOrder order = wxOrderService.getWxOrderByOrderId(orderId);
		// 获取订单信息
		WechartOrderDetailInput orderInput = new WechartOrderDetailInput();
		orderInput.setMid(mid);
		orderInput.setOrderId(orderId);
		WechartOrderOutput orderOut = (WechartOrderOutput) wizarposOpenRestClient.post(orderInput, "/order/detail", WechartOrderOutput.class);								
		if (!SysConstants.OPEN_SUCCESS.equals(orderOut.getCode())) {
			// TODO 订单错误
		}
		WechartOrder order = orderOut.getResult();
		data.put("orderId", Function.getShowWxOrderId(orderId));
		data.put("amount", Utils.formatAmount(order.getAmount()));
		data.put("mid", order.getMid());
		data.put("openId", order.getOpenId());
		return new ModelAndView("order/order_unpay", data);
	}

	// 修改收货地址
	/*@RequestMapping(value = "/update_order")
	public ModelAndView updateConfirmOrder(
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "orderId") String orderId,
			@RequestParam(value = "cardId", required = false) String cardId,
			@RequestParam(value = "id", required = false) String id) {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> items_detail = new HashMap<String, Object>();
		Map<String, Object> items_num = new HashMap<String, Object>();
		Map<String, Object> items = new HashMap<String, Object>();
		WxOrder order = wxOrderService.getWxOrderByOrderId(orderId);
		String nums = null;
		double num = 0;
		String price = null;
		List<cn.congine.wizarpos.mall.model.WxOrderDetail> detail = wxOrderDetailService
				.getWxOrderDetailListByOrderId(order.getOrderId());
		for (cn.congine.wizarpos.mall.model.WxOrderDetail wxo : detail) {
			num += wxo.getAmount();
			nums = Utils.formatAmount(num);
			price = Utils.formatAmount(wxo.getPrice());
			ErpProduct erp = erpProductService.getErpProductById(wxo
					.getProductId());
			String url = erp.getPicUrl();
			items.put(wxo.getProductId(), url);
			items_num.put(wxo.getProductId(), price);
		}
		items_detail.put(order.getOrderId(), detail);
		MrtMerchantCard cardNo = mrtMerchantCardService.getMrtMerchantCard(mid,
				openId);
		Integer balance = cardNo.getBalance();
		WxAddress add = wxAddressService.getWxAddressId(id);
		order.setAddressId(add.getId());
		wxOrderService.update(order);
		String cardid = null;
		cardid = cardNo.getId();
		data.put("num", num);
		data.put("balance", balance);
		data.put("cardid", cardid);
		data.put("add", add);
		data.put("cardId", cardId);
		data.put("id", id);
		data.put("mid", mid);
		data.put("nums", nums);
		data.put("items", items);
		data.put("items_num", items_num);
		data.put("openId", openId);
		data.put("orderId", orderId);
		data.put("order", order);
		data.put("items_detail", items_detail);
		return new ModelAndView("order/confirm_order", data);

	}*/

	// 地址选择后回到订单
	@RequestMapping(value = "/return_order")
	public ModelAndView ruturnOrder(
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "cartId") String cartId,
			@RequestParam(value = "productId", required = false) String productId,
			@RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "cardId", required = false) String cardId,
			@RequestParam(value = "orderId", required = false) String orderId,
			HttpServletRequest httpRequest) {
		logger.debug("-------...返回订单" + mid);
		Map<String, Object> data = new HashMap<String, Object>();
//		SysMerchantDef merchantDef = sysMerchantDefService
//				.getSysMerchantDefByMid(mid);
		Utils.setSessionToken(httpRequest);
		// 立即购买
		if (productId != null && !productId.isEmpty()) {
//			ErpProduct product = erpProductService.getErpProductById(productId);
			MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
			producthotInput.setMid(mid);
			producthotInput.setProductId(productId);
			MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
			Merchandise product = null;
			if (SysConstants.OPEN_SUCCESS.equals(producthotOutput.getCode())) {
				List<Merchandise> products = producthotOutput.getResult();
				if (products != null && !products.isEmpty()) {
					product = products.get(0);
					WxShoppingCartItem cartitem = new WxShoppingCartItem();
//					cartitem.setPicUrl(getPrituce(productId));
					if (StringUtils.isEmpty(product.getPicUrl())) {
						cartitem.setPicUrl(SysConstants.DEFAULT_PICTURE);
					} else {
						cartitem.setPicUrl(Function.dealGridPicUrl(product.getPicUrl(), 150, 150));
					}
					cartitem.setProductId(productId);
					cartitem.setProductName(product.getName());
					cartitem.setProductNum(1);
/*					int amount = Integer.valueOf(product.getMemberPrice());
					String amountStr = Utils.formatAmount(amount);*/					
					String amountStr = product.getMemberPrice();					
					cartitem.setShowPrice(amountStr);
					List<cn.congine.wizarpos.mall.vo.WxShoppingCartItem> items = new ArrayList<cn.congine.wizarpos.mall.vo.WxShoppingCartItem>();
					items.add(cartitem);
//					WxAddress address = wxAddressService.getWxAddressId(id);
					WxAddress address = null;
					AddressDetailInput in = new AddressDetailInput();
					in.setMid(mid);
					in.setId(id);
					AddressDetailOutput out = (AddressDetailOutput) wizarposOpenRestClient.post(in, "/address/detail", AddressDetailOutput.class);								
					if (SysConstants.OPEN_SUCCESS.equals(out.getCode())) {
						address = (WxAddress) out.getResult();
					}
					data.put("address", address);
					data.put("mid", mid);
					data.put("openId", openId);
					data.put("sum", amountStr);
					data.put("items", items);
					data.put("cartId", cartId);
					data.put("cardId", cardId);
					data.put("productId", productId);
//					data.put("merchantDef", merchantDef);
					return new ModelAndView("order/order", data);
				}
			} else {
				// TODO
			}
			
		}

		// 购物车结算
		if (cartId != null && !cartId.isEmpty()) {
//			List<cn.congine.wizarpos.mall.vo.WxShoppingCartItem> items = wxShoppingCartItemService
//					.getWxShoppingCartItemListByCartId(cartId);
			GetShoppingCartInput input = new GetShoppingCartInput();
			input.setMid(mid);
			input.setOpenId(openId);
			GetShoppingCartOutput output = (GetShoppingCartOutput) wizarposOpenRestClient.post(input, "/wxshop/get_cart_list", GetShoppingCartOutput.class);								
			if (!SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
				if (SysConstants.NO_MEMBER.equals(output.getCode())) {
					data.put("mid", mid);
					data.put("openId", openId);
					return new ModelAndView("card/receive_card", data);
				}
			}
			// 获取购物车里的商品信息
			List<WxShoppingCartItem> items = output.getWxShoppingCartItemList();
			
			
			int amount = 0;
			if (items != null && !items.isEmpty()) {
				for (WxShoppingCartItem cartitem : items) {
					String product_id = cartitem.getProductId();
					amount += cartitem.getProductPrice()
							* cartitem.getProductNum();
					cartitem.setShowPrice(cartitem.getShowPrice());//modify
//					cartitem.setPicUrl(getPrituce(product_id));
					if (StringUtils.isEmpty(cartitem.getPicUrl())) {
						cartitem.setPicUrl(SysConstants.DEFAULT_PICTURE);
					} else {
						cartitem.setPicUrl(Function.dealGridPicUrl(cartitem.getPicUrl(), 150, 150));
					}
				}
			}
			String sumStr = Utils.formatAmount(amount);// 所有商品总金额

//			MrtMerchantCard card = mrtMerchantCardService.getMrtMerchantCard(
//					mid, openId);
//			String card_id = card == null ? "" : card.getId();
//			WxAddress wx = wxAddressService.getDefaultWxAddress(card_id);
//
//			// Map<String, Object> data = new HashMap<String, Object>();
//			if (wx != null) {
//				data.put("username", wx.getUserName());
//				data.put("phone", wx.getPhone());
//			}
			
//			WxAddress address = wxAddressService.getWxAddressId(id);
			WxAddress address = null;
			AddressDetailInput in = new AddressDetailInput();
			in.setMid(mid);
			in.setId(id);
			AddressDetailOutput out = (AddressDetailOutput) wizarposOpenRestClient.post(in, "/address/detail", AddressDetailOutput.class);								
			if (SysConstants.OPEN_SUCCESS.equals(out.getCode())) {
				address = (WxAddress) out.getResult();
			}
			data.put("address", address);
			data.put("mid", mid);
			data.put("openId", openId);
			data.put("cardId", cardId);
			data.put("cartId", cartId);
			data.put("sum", sumStr);
			data.put("items", items);
//			data.put("merchantDef", merchantDef);
			return new ModelAndView("order/order", data);
		}

		if (orderId != null && !orderId.isEmpty()) {
//			List<WxOrderDetail> details = wxOrderDetailService
//					.getWxOrderDetailListByOrderId(orderId);
//			WxOrder wxOrder = wxOrderService.getWxOrderByOrderId(orderId);
			WechartOrderDetailInput orderInput = new WechartOrderDetailInput();
			orderInput.setMid(mid);
			orderInput.setOrderId(orderId);
			WechartOrderOutput orderOut = (WechartOrderOutput) wizarposOpenRestClient.post(orderInput, "/order/detail", WechartOrderOutput.class);								
			if (!SysConstants.OPEN_SUCCESS.equals(orderOut.getCode())) {
				// TODO 订单错误
			}
			WechartOrder wxOrder = orderOut.getResult();
			List<WxOrderDetail> details = wxOrder.getOrderDetail();
			
			int amount = Integer.valueOf(wxOrder.getAmount());
			List<WxShoppingCartItem> items = new ArrayList<WxShoppingCartItem>();
			if (details != null && !details.isEmpty()) {
				for (WxOrderDetail item : details) {
					WxShoppingCartItem cartItem = new WxShoppingCartItem();
					String proId = item.getProductId();
					cartItem.setShowPrice(Utils.formatAmount((item.getPrice())));
//					cartItem.setPicUrl(getPrituce(proId));
					if (StringUtils.isEmpty(item.getPicUrl())) {
						cartItem.setPicUrl(SysConstants.DEFAULT_PICTURE);
					} else {
						cartItem.setPicUrl(Function.dealGridPicUrl(item.getPicUrl(), 150, 150));
					}
					cartItem.setProductId(proId);
					cartItem.setProductName(item.getProductName());
					cartItem.setProductNum(item.getQty());
					cartItem.setProductPrice(item.getPrice());
					items.add(cartItem);
				}
			}
			String sumStr = Utils.formatAmount(amount);// 所有商品总金额

			WxAddress address = null;
			AddressDetailInput in = new AddressDetailInput();
			in.setMid(mid);
			in.setId(id);
			AddressDetailOutput out = (AddressDetailOutput) wizarposOpenRestClient.post(in, "/address/detail", AddressDetailOutput.class);								
			if (SysConstants.OPEN_SUCCESS.equals(out.getCode())) {
				address = (WxAddress) out.getResult();
				data.put("address", address);
			}

			data.put("orderId", orderId);
			data.put("mid", mid);
			data.put("openId", openId);
			data.put("cardId", cardId);
			data.put("cartId", "");
			data.put("sum", sumStr);
			data.put("items", items);
//			data.put("merchantDef", merchantDef);
			return new ModelAndView("order/order", data);
		}

		return new ModelAndView("error").addObject("err_message", "系统错误");
	}

}
